package com.msb.service.impl;

import com.msb.dto.UserDTO;
import com.msb.mapper.UserRoleMapper;
import com.msb.pojo.User;
import com.msb.mapper.UserMapper;
import com.msb.pojo.UserRole;
import com.msb.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author chshh
 * @since 2022-10-21
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Resource
    private UserRoleMapper userRoleMapper;

    @Resource
    private UserMapper userMapper;

    @Override
    public Integer saveOrUpdate(UserDTO userDTO, HttpSession session) throws Exception {
        //1.添加用户信息
        User user = userDTO.getUser();
        if (session.getAttribute("userId") != null){
            user.setUserId((Integer) session.getAttribute("userId"));
            userRoleMapper.deleteById((Integer) session.getAttribute("userId"));
        }else {
            //1.2 密码加密
            String salt = UUID.randomUUID().toString();
            Md5Hash md5Hash = new Md5Hash(user.getPassword(), salt);
            user.setPassword(md5Hash.toString());
            user.setU1(salt);
        }

        this.saveOrUpdate(user);

        // 2.分配用户和角色的关联关系
        // 获取分配给当前用户的角色信息
        List<Integer> roleIds = userDTO.getRoleIds();
        if(roleIds != null && roleIds.size() > 0){
            // 表示分配的有角色信息
            for (Integer roleId : roleIds) {
                // 将用户和角色的关联关系保存到 t_user_role 中
                UserRole userRole = new UserRole();
                userRole.setUserId(user.getUserId());
                userRole.setRoleId(roleId);
                userRoleMapper.insert(userRole);
            }
        }
        return 1;
    }

    @Override
    public User login(String userName) {
        HashMap<String , Object> map = new HashMap<>();
        map.put("userName",userName);
        List<User> users = userMapper.selectByMap(map);
        if (users != null && users.size()>0){
            return users.get(0);
        }
        return null;
    }

}
